package cn.com.joycode.nimble.admin.security.filter;

import cn.com.joycode.nimble.admin.security.authentication.NimbleAdminAuthenticationToken;
import cn.com.joycode.nimble.admin.security.configuration.NimbleAdminWebSecurityConfigurerAdapter;
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class NimbleAdminAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {

    public NimbleAdminAuthenticationProcessingFilter() {
        super(new AntPathRequestMatcher(NimbleAdminWebSecurityConfigurerAdapter.LOGIN_API_URL, HttpMethod.POST.name()));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        String contentType = httpServletRequest.getContentType();
        log.info("请求认证:{}", contentType);
        String content = IoUtil.read(httpServletRequest.getInputStream(), StandardCharsets.UTF_8);
        log.info("请求内容:{}", content);
        NimbleAdminAuthenticationToken token = new NimbleAdminAuthenticationToken();
        return getAuthenticationManager().authenticate(token);
    }
}
